var articleId="";
$(function(){
	farmatDate();
	showAllArticlesCount("","","");
	
	// 点击标题查看文章内容
	$("#center").on('click','.title',function() {
		var id=$(this)[0].id;
		showArticle(id);
	});
	
	// 绑定点击标签查询功能
	$("#center").on('click','.post-tag',function() {
		var tagName=$(this).text();
		var menuId="";
		var title="";
		showAllArticlesCount(menuId,tagName,title)
	});
	
	$("#menu").tree({
		onClick : function(node) {
			var nodeId=node.id;
			if("1"==nodeId){
				showAllArticlesCount("","","");
			}else{
				// 点击目录获取文章
				showAllArticlesCount(node.id,"","")
			}
		}
	});

	// 动态创建评论块
	$('#center').on('click','.plBtn',saveComment);
	
	// 删除评论块
    $('#center').on('click','.removeBlock',removeComment);
	
    // 动态创建回复块
    $('#center').on('click','.pl-hf',createAnswer);

    // 保存回复
    $('#center').on('click','.hf-pl',saveAnswer);
    
});

// 获取文章总数
function showAllArticlesCount(menuId,tagId,title){
	var datas={
		'menuId':menuId,
		'tagId':tagId,
		'title':title
	};
	$.ajax({
		url:'article/getArticlesCount.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				var totalCount=result.data;
				showArticleList(totalCount,menuId,tagId,title);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
}

// 获取文章数据
function showAllArticles(menuId,tagId,title,pageNum,pageSize){
	var datas={
		'menuId':menuId,
		'tagId':tagId,
		'title':title,
		'page':pageNum,
		'pageSize':pageSize
	};
	$.ajax({
		url:'article/getArticles.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			console.log(result);
			if(result.state==0){
				var articles=result.data;
				showArticleListMsg(articles);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
}

// 获取文章内容
function showArticle(id){
	var datas={
		"id":id
	};
	$.ajax({
		url:'article/getArticleMsg.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				var article=result.data;
				showArticleContent(article);
				// 统计文章访问量
				statistAccessCount(id);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
}

// 访问文章时,访问量+1
function statistAccessCount(articleId){
	var datas={
			"articleId":articleId
		};
		$.ajax({
			url:'article/articleVisistAdd.do',
			data:datas,
			type:'post',
			dataType:'json',
			success: function(result){
				if(result.state==0){
//					console.log(result);
				}
			},
			error: function(e){
				alert("通信失败!");
			}
		});
}

// 将文章内容显示出来
function showArticleContent(article){
	articleId=article.id;
	$("#center").html("");
	var title = article.title;
	var id = article.id;
	var author = article.author;
	var tagIds = article.tagId;
	var lastModifyTime = article.lastModifyTime;

	lastModifyTime = new Date(parseFloat(lastModifyTime)).format("yyyy-MM-dd hh:mm:ss");
	
	var tagA="";
	if(tagIds!=null){
		var tagLists = tagIds.split(",");
		tagLists.forEach(function(value){
			tagA += '<a class="post-tag">'+value+'</a>';
		})
	}
	
	var titleDiv='<div><div class="title">'+
					    '<h1>'+title+'</h1>'+
					    '<div class="tags">'+tagA+'</div>'+
					    '</div>'+
				  '</div>';
	
	$("#center").html(titleDiv);
	$("#center").append('<div style="padding:50px 30px">'+article.content+'</div>');
	addCollectBtn(id,author);
	
	$("#center").append('<div id="comment_zoom" style="padding:50px 30px">'+
			'<div id="commentShow"></div><div id="comment_have"></div></div>');
	
// 评论区域
	var reviewAreaDiv='<div class="reviewArea clearfix">'+
					        '<textarea class="content comment-input" '+
					        ' placeholder="Please enter a comment&hellip;" onkeyup="keyUP(this)"></textarea>'+
					        '<a href="javascript:;" class="plBtn">评论</a>'+
					    '</div>';
	$("#commentShow").append(reviewAreaDiv);
	$('.content').flexText();
	showComments(id);
	
}

// textarea限制字数
function keyUP(t){
    var len = $(t).val().length;
    if(len > 500){
        $(t).val($(t).val().substring(0,500));
    }
    
}

// 展示已有的评论和回复
function showComments(articleId){
	
	var datas={
			"articleId":articleId
		};
		$.ajax({
			url:'comment/getComment.do',
			data:datas,
			type:'post',
			dataType:'json',
			success: function(result){
				if(result.state==0){
					var comments=result.data;
					showCommentsInArticle(comments);
				}
			},
			error: function(e){
				alert("通信失败!");
			}
		});
}

// 将评论显示在页面
function showCommentsInArticle(comments){
	for(var i=0;i<comments.length;i++){
		var comment=comments[i];
		var createTime = new Date(parseFloat(comment.createTime)).format("yyyy-MM-dd hh:mm:ss");
		var user = getUserDetails(comment.userId);
		var commentMsgDiv='<div class="comment-show">'+
					        '<div class="comment-show-con clearfix">'+
							    '<div class="comment-show-con-img pull-left"><img src="images/header-img-comment_03.png" alt=""></div>'+		// 头像
							    '<div class="comment-show-con-list pull-left clearfix">'+
							        '<div class="pl-text clearfix">'+
							            '<a href="#" class="comment-size-name" title="'+user.id+'">'+user.nick+' : </a>'+
							            '<span class="my-pl-con" title="'+comment.id+'">&nbsp;'+comment.content+'</span>'+
							        '</div>'+
							        '<div class="date-dz">'+
							            '<span class="date-dz-left pull-left comment-time">'+createTime+'</span>'+
							            '<div class="date-dz-right pull-right comment-pl-block">'+
							                '<a href="javascript:;" class="removeBlock">删除</a>'+
							                '<a href="javascript:;" class="date-dz-pl pl-hf hf-con-block pull-left">回复</a>'+
							            '</div>'+
							        '</div>'+
							        '<div class="hf-list-con" id="hf_list_con_'+i+'"></div>'+
							    '</div>'+
							'</div>'+
						'</div>';
		
		$("#comment_have").append(commentMsgDiv);	
		// textarea高度自适应
		$('.content').flexText();
		
		var answers = comment.answers;
		
		for(var j=0;j<answers.length;j++){
			var answer = answers[j];
			var replyUserId = answer.replyUserId;
			var id = answer.id;
			var replyUser = getUserDetails(replyUserId);
			var user = getUserDetails(answer.userId);
			var createTime = new Date(parseFloat(answer.createTime)).format("yyyy-MM-dd hh:mm:ss");
			var oAt = '回复<a href="#" class="atName">@'+replyUser.nick+'</a> : '+answer.content;
			
			var answerDiv='<div class="all-pl-con">'+
							'<div class="pl-text hfpl-text clearfix">'+
								'<a href="#" class="comment-size-name" title="'+user.id+'">'+user.nick+' : </a>'+
								'<span class="my-pl-con" title="'+comment.id+'">'+oAt+'</span></div>'+
							'<div class="date-dz"> '+
								'<span class="date-dz-left pull-left comment-time">'+createTime+'</span> '+
								'<div class="date-dz-right pull-right comment-pl-block" id="'+id+'"> '+
									'<a href="javascript:;" class="removeBlock">删除</a> '+
									'<a href="javascript:;" class="date-dz-pl pl-hf hf-con-block pull-left">回复</a> '+
								'</div> '+
							'</div>'+
						'</div>';
			
			$('#hf_list_con_'+i).append(answerDiv);
		}
	}
							
}

// 动态创建回复框
function createAnswer(){
	// 获取回复人的名字
	var fhName = $(this).parents('.date-dz-right').parents('.date-dz').siblings('.pl-text').find('.comment-size-name').html();
	var fhHtml = '<div class="hf-con pull-left"> '+
					'<textarea class="content comment-input hf-input" placeholder="" onkeyup="keyUP(this)"></textarea> '+
					'<a href="javascript:;" class="hf-pl">评论</a>'+
				'</div>';
	// 显示回复
	if($(this).is('.hf-con-block')){
		$(this).parents('.date-dz-right').parents('.date-dz').append(fhHtml);
		$(this).removeClass('hf-con-block');
		$('.content').flexText();
		$(this).parents('.date-dz-right').siblings('.hf-con').find('.pre').css('padding','6px 15px');
	}else {
		$(this).addClass('hf-con-block');
		$(this).parents('.date-dz-right').siblings('.hf-con').remove();
	}
	
}

// 删除评论
function removeComment(){
	var id='';
	var type='';
	var oT =  $(this).parents('.date-dz-right').parents('.date-dz').parents('.all-pl-con');
	if(oT.length >= 1){
		var answer = $(this).parents('.date-dz-right');
		var answerId=$(answer)[0].id;
		id=answerId;
		type='answer';
	 }else {
		var comment = $(this).parents('.date-dz-right').parents('.date-dz').siblings('.pl-text').find('.my-pl-con');
		var commentId=$(comment)[0].title;
		id=commentId;
		type='comment';
	 }
	 removeCommentOrAnswer(id,type);
}

//删除评论\回复
function removeCommentOrAnswer(id,type){
	var contentDialog='';
	var headDialog='';
	if("comment"==type){
		headDialog="评论";
		contentDialog="确定删除评论及其所有的回复吗?";
	}
	if("answer"==type){
		headDialog="回复";
		contentDialog="确定删除该回复吗?";
	}
	
	var btnFn = function() {
		var datas={
				"id":id,
				"type":type
			};
		$.ajax({
			url:'comment/removeComments.do',
			data:datas,
			type:'post',
			dataType:'json',
			success: function(result){
				if(result.state==0){
					$("#comment_have").html('');
					showComments(articleId);
				}
			},
			error: function(e){
				alert("通信失败!");
			}
		});
		
		easyDialog.close();
		return false;
	};
	
	easyDialog.open({
		container : {
			header : headDialog,
			content : contentDialog,
			yesFn : btnFn,
			noFn : true
		}
	});
	
}

// 保存评论信息
function saveComment(){
// console.log(articleId);
	var commentContent = $(".comment-input").val().trim();
	if(commentContent==null||commentContent.length==0||commentContent==undefined){
		messageShow("评论","评论内容为空,请输入评论内容!");
		$(".comment-input").val('');
		return;
	}
	var userId = getCookie("userId");
	var datas={
			"articleId":articleId,
			"userId":userId,
			"commentContent":commentContent
		};
	$.ajax({
		url:'comment/saveComment.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				$("#comment_have").html('');
				$(".comment-input").val('');
				showComments(articleId);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
}

// 保存回复
function saveAnswer(){
	var answerContent = $('.hf-input').val().trim();

	if(answerContent==null||answerContent.length==0||answerContent==undefined){
		messageShow("回复","回复内容为空,请输入回复内容!");
		$('.hf-input').val('');
		return;
	}
	
	var userId = getCookie("userId");
	var comment = $(this).parents('.date-dz').siblings('.pl-text').find('.my-pl-con');
	var replyUser = $(this).parents('.date-dz').siblings('.pl-text').find('.comment-size-name');
	var commentId=$(comment)[0].title;
	var replyUserId=$(replyUser)[0].title;
	
	var datas={
			"userId":userId,
			"commentId":commentId,
			"replyUserId":replyUserId,
			"answerContent":answerContent
		};
	$.ajax({
		url:'comment/saveAnswer.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				var answer=result.data;
				$("#comment_have").html('');
				showComments(articleId);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
}

// 获取用户详情
function getUserDetails(userId){
	var user="";
	var datas={
		"userId":userId	
	};
	$.ajax({
		url:'user/getUserDetails.do',
		data:datas,
		async:false,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				user=result.data;
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
	return user;
}

// 增加左侧悬浮按钮
function addCollectBtn(articleId,author){
	
	var collectDiv='<div class="slide" id="suspend">'+
						'<ul class="icon">'+
							'<li class="sc" style="text-align:center;line-height:49px">未收藏</li>'+
							'<li class="use yy"><p id="useful">10</p><p>有用</p></li>'+
							'<li class="use wy"><p id="unuseful">1</p><p>无用</p></li>'+
						'</ul></div>';	
	$("#center").append(collectDiv);
	
	initArticleMsgSuspend(articleId,author);
	
	// 收藏
	$("#suspend").on('click','.sc',function() {
		var collectState="";
		var li=$($(this)[0]);
		var liText=li.text();
		if("未收藏"==liText){
			collectState="1";
		}else{
			collectState="0";
		}
		updateSuspend(articleId,author,collectState,"");
	});
	// 有用/无用按钮
	$("#suspend").on('click','.use',function() {
		var use = $($(this)[0]);
		if(use.hasClass('yy')){
			if(use.hasClass('check')){
				use.removeClass('check');
			}else{
				use.addClass('check');
				$('.wy').removeClass('check');
			}
		}
		if(use.hasClass('wy')){
			if(use.hasClass('check')){
				use.removeClass('check');
			}else{
				use.addClass('check');
				$('.yy').removeClass('check');
			}
		}
		
		var usefullState="0";
		var useValue = $('.check').text();
		if(useValue.indexOf('有用')>0){
			usefullState="1";
		}
		if(useValue.indexOf('无用')>0){
			usefullState="2";
		}
		updateSuspend(articleId,author,"",usefullState)
	});
}

function initArticleMsgSuspend(articleId,author){
	var datas={
			"articleId":articleId,
			"author":author
		};
	$.ajax({
		url:'article/getArticleMsgSuspend.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				var articleMsg=result.data;
				if(articleMsg!=null){
					initArticleMsg(articleMsg);
				}
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
	
	// 获取有用/无用数量
	var countDatas={
		"articleId":articleId,
	};
	$.ajax({
		url:'article/countArticleMsg.do',
		data:countDatas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				var articleCount=result.data;
				$("#useful").text(articleCount.useful);
				$("#unuseful").text(articleCount.unuseful);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
	
	
	
}

// 更新收藏\有用\无用 按钮
function updateSuspend(articleId,author,collectState,usefullState){
	var datas={
			"articleId":articleId,
			"author":author,
			"collectState":collectState,
			"usefullState":usefullState
		};
	$.ajax({
		url:'article/updateArticleMsgSuspend.do',
		data:datas,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				var articleMsg=result.data;
				changCollectBtn(articleMsg.collectState);
				changUseBtn(articleMsg.usefullState);
				initArticleMsgSuspend(articleId,author);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
}


// 初始化悬浮按钮的值
function initArticleMsg(articleMsg){
	var collectState = articleMsg.collectState;
	var usefullState=articleMsg.usefullState;
	
	changCollectBtn(collectState);
	changUseBtn(usefullState)
}

function changUseBtn(state){
	if("2"==state){
		$('.wy').addClass("check");
		$('.yy').removeClass("check");
	}else if("1"==state){
		$('.yy').addClass("check");
		$('.wy').removeClass("check");
	}else {
		$('.wy').removeClass("check");
		$('.yy').removeClass("check");
	}
}

// 修改collectBtn状态
function changCollectBtn(state){
	if("1"==state){
		$(".sc").addClass("check");;
		$(".sc").text('已收藏');
	}else{
		$(".sc").removeClass("check");
		$(".sc").text('未收藏');
	}
}

function showArticleList(totalCount,menuId,tagId,title){
	$("#center").html("");
	if(totalCount==0){
		$("#center").append('<div class="no_articles"><h1>There is no articles here!<h1></div>');
		return;
	}else{
		$("#center").append('<div id="articleZoom"></div>');
		$("#center").append('<div style="width:100%;" id="page"><div class="box" '
				+' style="float:right;width:60%;margin:20px 0px 0px 0px;" id="box"></div></div>');
		pageDiv(totalCount,menuId,tagId,title);
	}
}

// 分页
function pageDiv(totalCount,menuId,tagId,title){
	var pageSize=10;
	var totalPages = Math.ceil(totalCount/pageSize);
	$('#box').paging({
		initPageNo: 1, // 初始页码
		totalPages: totalPages, // 总页数
		totalCount: '合计' + totalCount + '条数据', // 条目总数
		slideSpeed: 600, // 缓动速度。单位毫秒
		jump: true, // 是否支持跳转
		callback: function(page) { // 回调函数
			showAllArticles(menuId,tagId,title,page,pageSize)
		}
	})
}

function showArticleListMsg(articles){
	$("#articleZoom").html("");
	var len = articles.length;
	for(var i=0;i<len;i++){
		var article = articles[i];
		
		var title = article.title;
		var id = article.id;
		var visitNum = article.visitNum;
		var authorId = article.author;
		var user = getUserDetails(authorId);
		
		var tagIds = article.tagId;
		var lastModifyTime = article.lastModifyTime;
		lastModifyTime = new Date(parseFloat(lastModifyTime)).format("yyyy-MM-dd hh:mm:ss");
		
		var tagA="";
		console.log(tagIds);
		if(tagIds!=null){
			var tagLists = tagIds.split(",");
			tagLists.forEach(function(value){
				tagA += '<a class="post-tag">'+value+'</a>';
			})
		}
		// 获取评论数量
		var commentNum = statistCommentsNum(id);
		
		var divList='<div class="question-summary narrow">'+
						'<div class="cp">'+
						    '<div class="status answered">'+
						        '<div class="mini-counts"><span title="">'+commentNum+'</span></div>'+
						        '<div>comments</div>'+
						    '</div>'+
						    '<div class="views">'+
						        '<div class="mini-counts hot"><span title="">'+visitNum+'</span></div>'+
						        '<div class="hot">views</div>'+
						    '</div>'+
						'</div>'+
						'<div class="summary">'+
						    '<h2><a class="title" id='+id+'>'+title+'</a></h2>'+
						    '<div class="tags">'+tagA+'</div>'+
						    '<div class="started">'+
							    '<a>'+lastModifyTime+'</a>&nbsp;'+
							    '<a href="">'+user.nick+'</a>'+
						    '</div>'+
						'</div>'+
					'</div>';
		
		$("#articleZoom").append(divList);
	}
}

// 统计文章的评论数量
function statistCommentsNum(articleId){
	var commentNum='';
	var datas={'articleId':articleId};
	$.ajax({
		url:'article/statistCommentsNum.do',
		data:datas,
		async:false,
		type:'post',
		dataType:'json',
		success: function(result){
			if(result.state==0){
				commentNum=result.data;
			}else{
				alert(result.message);
			}
		},
		error: function(e){
			alert("通信失败!");
		}
	});
	return commentNum;
}

function farmatDate(){
	Date.prototype.format = function(format) {
        var o = {
            "M+" : this.getMonth() + 1,// month
            "d+" : this.getDate(),// day
            "h+" : this.getHours(),// hour
            "m+" : this.getMinutes(),// minute
            "s+" : this.getSeconds(),// second
            "q+" : Math.floor((this.getMonth() + 3) / 3),// quarter
            "S" : this.getMilliseconds()
        // millisecond
        };
        if (/(y+)/.test(format) || /(Y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for ( var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    };
	
}












